package virtualstock.player;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import virtualstock.exception.InvalidParameterException;
import virtualstock.exception.PlayerNotFoundException;
import virtualstock.request.GameController;
import virtualstock.util.GameDetails;

/**
 * Servlet implementation class PlayerControlServlet
 */
public class PlayerControlServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@EJB
	private GameController gameController;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PlayerControlServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    private void processListGame(Long playerID, HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
		PrintWriter out = response.getWriter();
		
		List<GameDetails> gameList = null;
		try {
			gameList = gameController.getGamesOfPlayer(playerID);
			System.out.println("num of games: " + gameList.size());
		} catch (InvalidParameterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (PlayerNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		out.println("<h2><span>List of games you have current involved</span></h2>");
		out.println("<form name=\"gameRadioForm\" action=\"GamePlayServlet\"  method='post' onSubmit=\"return checkedValue(this)\">");
		out.println("<table id='gameListTable' border='3'>");
		out.println("<tr >");
		out.println("    <th bgcolor=>select</th>");
		out.println("    <th bgcolor=>Name</th>");
		out.println("    <th bgcolor=>CreatorID</th>");
//		out.println("    <th bgcolor=>MaxPlayer</th>");
		out.println("    <th bgcolor=>InitBalance</th>");
		out.println("    <th bgcolor=>StartDate</th>");
		out.println("    ");
		out.println("</tr>");
		for (Iterator<GameDetails> it = gameList.iterator(); it.hasNext(); ) {
			GameDetails details = it.next();
			out.println("<tr>");
			out.println("    <td><input type=\"radio\" name=\"gameID\" value=\"" + details.getGameID() + "\" /></td>"); 
			out.println("    <td>" + details.getGameName() + "&nbsp;&nbsp;</td>"); 
			out.println("    <td>" + details.getCreator() + "&nbsp;&nbsp;</td>"); 
//			out.println("    <td>" + details.getMaxPlayer() + "&nbsp;&nbsp;</td>"); 
			out.println("    <td>" + details.getInitialBalance() + "&nbsp;&nbsp;</td>");
			out.println("    <td>" + details.getStartDate() + "&nbsp;&nbsp;</td>");
			out.println("</tr>"); 	
		}
		out.println("</table>");
		out.println("<input type='submit' value='resume'/>");
		out.println("</form>");
		out.println("<br />");
		
	}
	
	private void processCreateGame(Long playerID, HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
		PrintWriter out = response.getWriter();
		
		out.println("<h2><span>Create a new game</span></h2>");
		out.println("<form id=\"createNewGameForm\" action=\"CreateNewGameServlet\" method=\"post\" onSubmit=\"return checkform()\">");
		out.println("	<div class=\"form_field\">");
		out.println("	<strong>creator</strong>");
		out.println("	<input type=\"text\" id = \"creator\" name=\"creator\" size=\"30\" value=\"" + playerID + "\" readonly/>");
		out.println("	</div>");
		out.println("");
		out.println("	<div class=\"form_field\">");
		out.println("	<strong>Name</strong>");
		out.println("	<input type=\"text\" id = \"name\" name=\"name\" size=\"30\" maxlength=\"30\" />");
		out.println("	</div>");
		/*out.println("");
		out.println("	<div class=\"clearthis\">&nbsp;</div>");
		out.println("");
		out.println("	<div class=\"form_field\">");
		out.println("	<strong>Max player</strong>");
		out.println("	<div id=\"strong\">");
		out.println("	<select name=\"maxPlayer\">");
		out.println("		<option value=\"1\" selected>1</option>");
		out.println("		<option value=\"2\">2</option>");
		out.println("		<option value=\"3\">3</option>");
		out.println("		<option value=\"4\">4</option>");
		out.println("		<option value=\"5\">5</option>");
		out.println("		<option value=\"10\">10</option>");
		out.println("		<option value=\"20\">20</option>");
		out.println("		<option value=\"30\">30</option>");
		out.println("		<option value=\"40\">40</option>");
		out.println("		<option value=\"50\">50</option>");
		out.println("		<option value=\"100\">100</option>");
		out.println("	</select>");
		out.println("	</div>");
		*/out.println("	");
		out.println("	<div class=\"clearthis\">&nbsp;</div>");
		out.println("	");
		out.println("	<div class=\"form_field\">");
		out.println("	<strong>Initial balance</strong>");
		out.println("	<input type=\"text\" id = \"initialBalance\" name=\"initialBalance\" size=\"30\" maxlength=\"8\" />");
		out.println("	</div>");
		out.println("	");
		out.println("	<div class=\"clearthis\">&nbsp;</div>");
		out.println("	");
		out.println("   <div class=\"form_field\">");
        out.println("   <input type=\"submit\" id=\"GameCreation\" value=\"create\" />");
        out.println("   </div>");
        out.println("   ");
        out.println("</form>");
	}
	
	private void processJoinGame(Long playerID, HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
		PrintWriter out = response.getWriter();
		
		List<GameDetails> allAvailableGames = gameController.getAllAvailableGames();
		
		List<GameDetails> gameList = null;
		try {
			gameList = gameController.getGamesOfPlayer(playerID);
		} catch (InvalidParameterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (PlayerNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(allAvailableGames != null){
			allAvailableGames.removeAll(gameList);
		}
		/*
		try {
			gameList = gameController.getGamesOfPlayer(playerID);
		} catch (InvalidParameterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (PlayerNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		*/
		out.println("<h2><span>List of games that you can join.</span></h2>");
		out.println("<form name=\"joinGameRadioForm\" action=\"JoinGameServlet\"  method='post' onSubmit=\"return checkedValue(this)\">");
		out.println("<table id='allGameListTable' border='3'>");
		out.println("<tr >");
		out.println("    <th bgcolor=>select</th>");
		out.println("    <th bgcolor=>Name</th>");
		out.println("    <th bgcolor=>CreatorID</th>");
//		out.println("    <th bgcolor=>MaxPlayer</th>");
		out.println("    <th bgcolor=>InitBalance</th>");
		out.println("    <th bgcolor=>StartDate</th>");
		out.println("    ");
		out.println("</tr>");
		if(allAvailableGames != null){
			for (Iterator<GameDetails> it = allAvailableGames.iterator(); it.hasNext(); ) {
				GameDetails details = it.next();
				out.println("<tr>");
				out.println("    <td><input type=\"radio\" name=\"gameID\" value=\"" + details.getGameID() + "\" /></td>"); 
				out.println("    <td>" + details.getGameName() + "&nbsp;&nbsp;</td>"); 
				out.println("    <td>" + details.getCreator() + "&nbsp;&nbsp;</td>"); 
//				out.println("    <td>" + details.getMaxPlayer() + "&nbsp;&nbsp;</td>"); 
				out.println("    <td>" + details.getInitialBalance() + "&nbsp;&nbsp;</td>");
				out.println("    <td>" + details.getStartDate() + "&nbsp;&nbsp;</td>");
				out.println("</tr>"); 	
			}
		}
		out.println("</table>");
		out.println("<input type='submit' value='join'/>");
		out.println("</form>");
		out.println("<br />");
		/*out.println("Input the Game ID you want to join:");
		out.println("<div id=\"link-password\">");
		out.println("<input type=\"button\" onclick=\"javascript:createGame(${sessionScope.playerDetails.playerID});\" value=\"join\"/>");
		out.println("</div>");
		*//*
		out.println("<form id='joinGameForm' action='JoinGameServlet' method='post'>");
		out.println("<table>");
		out.println("	<tr>");
		out.println("		<td>Game ID:</td>");
		out.println("		<td><input type='text' id='gameID' name='gameID' /></td>");
		out.println("	</tr>");
		out.println("</table>");
		out.println("<input type='submit' id='GameJoin' value='Join' />");
		out.println("</form>");
		out.println("<br>");
		*/
	
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		System.out.println("I'm in doGet of PlayerControlServlet");
		
		Long id = null;
		String type = "";
		String query = request.getQueryString();
		Matcher m = Pattern.compile("type=(\\w+)&id=(\\d+)").matcher(query);
		if (m.find()) {
			type = m.group(1);
			id = new Long(m.group(2));
			if (type.equals("list")) {
				processListGame(id, request, response);
			} else if (type.equals("create")) {
				processCreateGame(id, request, response);
			} else if (type.equals("join")) {
				processJoinGame(id, request, response);
			}
		} else {
			out.print("didn't find");
		}
		response.setHeader("Cache-Control", "no-cache");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}
